# Copyright (C) Maciej Suminski <orson@orson.net.pl>
# Copyright (C) 2020 Seth Hillbrand <seth@kipro-pcb.com>
# Copyright (C) 2023 Andrew Lutsenko <anlutsenko@gmail.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, you may find one here:
# https://www.gnu.org/licenses/gpl-3.0.html
# or you may search the http://www.gnu.org website for the version 3 license,
# or you may write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA


import re


# regex to find the build version information,
# only if not preceded with verbatim mode tag (```)
re_build_info = re.compile(r'(?<!```)(?<!plaintext)?(?<![\r\n])((?:^[\r\n]*^[ \t]*Application: .+)(?:(?:Build (?:Info|settings):|Version:.+|Libraries:|Platform:.+)\n?(?:[ \t]+[^\n]+\n?)+\n?)*)+',
                           re.DOTALL | re.MULTILINE)

re_any_build_info = re.compile(r'((?:^[ \t`]*Application: .+)(?:(?:Build (?:Info|settings):|Version:.+|Libraries:|Platform:.+|Locale:)\n?(?:[ \t]+[^\n]+\n?)*)+)',
                               re.DOTALL | re.MULTILINE)

re_version_string = re.compile(r'(?:Version:\s*\(?([\d.]+).*?build$)',
                               re.MULTILINE)


def has_build_info(description: str) -> bool:
    if not re_any_build_info.search(description):
        return False

    return True


def fix_build_info(description: str) -> str:
    '''Wraps build info with verbatim mode tags (if needed).'''
    if not re_build_info.search(description):
        return None

    def verbatim_wrap(match):
        return '```\n{0}\n```'.format(match.group(0))

    return re_build_info.sub(verbatim_wrap, description)


def get_version(description: str) -> str:
    version = re_version_string.search(description)

    if not version:
        return ''

    return version.group(1)


# def get_next_version(description: str) -> str:
#     version = get_version(description)
#
#     if not version:
#         return ''
#
#     kmaj, kmin, kbug = KICAD_VERSION.split('.')
#     maj, min, bug = version.split('.')
#
#     if min == 99:
#         return '.'.join((str(int(kmaj) + 1), '0'))
#
#     return '.'.join((kmaj, kmin, str(max(int(kbug), int(bug)) + 1)))
